//
//  UIImage+Extension.swift
//  DoctorEPlus
//
//  Created by 王林波 on 2020/11/20.
//

import Foundation
import UIKit
import PhotosUI

extension UIImage {
  
    /**图片切割处理,等宽高*/
    func divedeImageFit() -> UIImage {
        if self.size.height > self.size.width{
            let cg_image = (self.cgImage?.cropping(to: CGRect(x: 0, y: abs(self.size.height-self.size.width)/2.0, width: self.size.width, height: self.size.width)))!
            return UIImage.init(cgImage: cg_image)
        }else {
            let cg_image = (self.cgImage?.cropping(to: CGRect(x: abs(self.size.height - self.size.width)/2.0, y: 0, width: self.size.height, height: self.size.height)))!
            return UIImage.init(cgImage: cg_image)
        }
    }
    
    /**图片切割处理,自定义宽高*/
    func cutFoSize(_ size: CGSize) -> UIImage {
        if self.size.height > self.size.width{
            
            let height_ = (self.size.width*size.height)/size.width
            
            let cg_image = (self.cgImage?.cropping(to: CGRect(x: 0, y: abs(self.size.height-height_)/2.0, width: self.size.width, height: height_)))!
            return UIImage.init(cgImage: cg_image)
        }else if self.size.height == self.size.width { // 等宽高
            if size.width == size.height {
                return self
            }else {
                
                let cg_image = (self.cgImage?.cropping(to: CGRect(x:0, y:0, width: self.size.width, height: self.size.height)))!
                return UIImage.init(cgImage: cg_image)
            }
        }
        else {
            let width = self.size.height*size.width/size.height
            
            let cg_image = (self.cgImage?.cropping(to: CGRect(x: abs(self.size.width - width)/2.0, y: 0, width: width, height: self.size.height)))!
            return UIImage.init(cgImage: cg_image)
        }
    }
    
    static func createImage(color: UIColor, size: CGSize) -> UIImage? {

        let rect = CGRect(origin: CGPoint.zero, size: size)
        UIGraphicsBeginImageContext(size)
        defer {
            UIGraphicsEndImageContext()
        }
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
    
    func fixOrientation() -> UIImage {
        var image = self
        if self.imageOrientation == .up {
            return image
        }
        var transform = CGAffineTransform.identity
        switch self.imageOrientation {
        case .down, .downMirrored:
            transform = transform.translatedBy(x: image.size.width, y: image.size.height)
            transform = transform.rotated(by: .pi / 2)
        case .left, .leftMirrored:
            transform = transform.translatedBy(x: image.size.width, y: 0)
            transform = transform.rotated(by: .pi / 2)
        case .right, .rightMirrored :
            transform = transform.translatedBy(x: 0, y: image.size.height)
            transform = transform.rotated(by: -.pi / 2)
        default:
            break
        }
        
        switch self.imageOrientation {
        case .upMirrored, .downMirrored:
            transform = transform.translatedBy(x: image.size.width,y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        case .rightMirrored, .leftMirrored:
            transform = transform.translatedBy(x: image.size.height,y: 0)
            transform = transform.scaledBy(x: -1, y: 1)
        default:
            break
        }
        
        let ctx = CGContext(data: nil , width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: 0, space: image.cgImage!.colorSpace!, bitmapInfo: image.cgImage!.bitmapInfo.rawValue)
        
        ctx!.concatenate(transform)
        
        switch image.imageOrientation {
        case .left, .leftMirrored, .right, .rightMirrored:
            ctx?.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: image.size.height, height: image.size.width))
        default:
            ctx?.draw(image.cgImage!, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height))
        }
        
        let cgImage = ctx!.makeImage()
        image = UIImage(cgImage: cgImage!)
        return image
    }
    
    func clipImgRadius(radius: CGFloat) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.size, false, 1.0)
        UIBezierPath.init(roundedRect: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height), byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius)).addClip()
        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}



extension PHAsset {
    func assetToImage(maxSize:CGSize, block: @escaping (UIImage?)->Void) {
        let imageManager = PHImageManager.default()
      
        if #available(iOS 13, *) {
            imageManager.requestImageDataAndOrientation(for: self, options: .none) { (imageData, dataUTI, orientation, dic) in
                if imageData != nil {
                    let image = UIImage.init(data: imageData!)
                    block(image!)
                }else {
                    block(nil)
                }
            }
        } else {
           let imageRequestOption = PHImageRequestOptions()
           
           // PHImageRequestOptions是否有效
           imageRequestOption.isSynchronous = true
           // 缩略图的压缩模式设置为无
           imageRequestOption.resizeMode = .none
           // 缩略图的质量为高质量，不管加载时间花多少
           imageRequestOption.deliveryMode = .highQualityFormat
           // 按照PHImageRequestOptions指定的规则取出图片
           imageManager.requestImage(for: self, targetSize: CGSize.init(width: maxSize.width, height: maxSize.height), contentMode: .aspectFill, options: imageRequestOption, resultHandler: {
               (result, _) -> Void in
            if result != nil {
                block(result!)
            }else {
                block(nil)
            }
           })
        }
    }
}
